/**
 * @Description:
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 05/05/25 PM9:26
 */
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, tap, catchError, throwError } from 'rxjs';
// import { tap } from 'rxjs/operators';
import { Request, Response } from 'express';
import { uuid } from 'sf-utils2';

@Injectable()
export class RequestIdInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();

    request.params._responseId = uuid();

    return next.handle().pipe(
      tap(() => {
        response.setHeader('X-Request-ID', request.params._responseId); // 返回给客户端
      }),
      catchError((error) => {
        response.setHeader('X-Request-ID', request.params._responseId); // 返回给客户端
        return throwError(() => error);
      }),
    );
  }
}
